<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="店铺卖家记号">
              <a-input placeholder="请输入卖家ID" v-model="queryParam.sellerId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="店铺名称">
              <a-input placeholder="请输入店铺名称" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="负责人">
              <!-- <j-multi-select-tag v-model="queryParam.director" :options="userDictOptions" placeholder="请输入并选择负责人" :maxTagCount="2"></j-multi-select-tag>   -->
              <a-select
                v-model="queryParam.directorArr"
                show-search
                mode="multiple"
                :filter-option="filterOption"
                placeholder="请输入并选择负责人"
                :maxTagCount="2"
                :maxTagTextLength="5"
                :allowClear="true"
              >
                <a-select-option v-for="item in userDictOptions" :key="item.value" :value="item.value">
                {{ item.label}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="成本中心">
                <a-select v-model="queryParam.costCenterId" placeholder="请选择成本中心" show-search option-filter-prop="children" :filter-option="filterOption">
                <a-select-option  v-for="(costCenter,index) in costCenterData" :key="index" :value="costCenter.id">{{costCenter.name}}</a-select-option>
              </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="站点">
                <!-- <j-select-multiple v-model="queryParam.site" placeholder="请选择站点" :options="storeSiteData"></j-select-multiple> -->
                <a-tree-select
                  v-model="queryParam.site"
                  style="width: 100%"
                  :tree-data="storeSiteData"
                  tree-checkable
                  :replaceFields="replaceFields"
                  :maxTagCount="2"
                  search-placeholder="请选择站点"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="授权状态">
                <j-select-multiple
                  v-model="queryParam.authStatus"
                  placeholder="请选择授权状态"
                  dictCode="oms_store_auth_status"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="同步状态">
                <j-select-multiple
                  placeholder="请选择同步状态"
                  v-model="queryParam.syncStatus"
                  dictCode="oms_store_sync_status"
                />
              </a-form-item>
            </a-col>
            <!-- <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="税费计入方式">
                <j-select-multiple
                  placeholder="请选择税费计入方式"
                  v-model="queryParam.taxWay"
                  dictCode="oms_store_tax_way"
                />
              </a-form-item>
            </a-col> -->
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="变更进度">
                <j-dict-select-tag v-model="queryParam.progressStatus" dictCode="oms_progress_status" placeholder="请选择变更进度"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="备注">
                <a-input v-model="queryParam.remark" placeholder="请输入备注关键词" :maxLength="60"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="9" :sm="24">
              <a-form-item>
                <span slot="label">
                  <a-select v-model="dateTime" style="width: 100%" @change="dateTimeSelect">
                    <a-select-option v-for="item in dateTimeData" :key="item.value" :value="item.value">
                      {{ item.title }}
                    </a-select-option>
                  </a-select>
                </span>
                <a-range-picker
                  v-model="dateTimeRange"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  show-time
                  @change="dateTimeChange"
                ></a-range-picker>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('店铺授权')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="handleBatchSetting">店铺设置</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :customRow="selectRowData"
      >
        <!-- 站点 -->
        <span slot="siteSlot" slot-scope="text, record">
          {{ record.regionName }} <span v-if="record.site"> - {{ record.siteName }}[{{ record.site }}]</span>
        </span>
        <!-- 授权状态 -->
        <span slot="authStatusSlot" slot-scope="text, record, index">
          <!-- error：授权异常 -->
          <span class="error-status" v-if="record.authStatus === 'error'">
            {{ record.authStatus_dictText }}
            <a-popover :visible="tipVisibleId === record.id" trigger="click">
              <template slot="title">
                <div class="error-status error-title">
                  异常原因<a-icon type="close" style="color: rgba(0, 0, 0, 0.85)" @click="tipVisibleId = null" />
                </div>
              </template>
              <template slot="content">
                {{ record.errorMsg }}
              </template>
              (<a @click="tipVisibleId = record.id">原因</a>)
            </a-popover>
            <a style="margin-left: 5px" @click="authAfreshHadnle(record)">重新授权</a>
          </span>
          <span v-else>{{ record.authStatus_dictText }}</span>
        </span>
        <!-- 同步状态 -->
        <span slot="syncStatusSlot" slot-scope="text, record">
          <a-popconfirm
            :title="`你确定要${record.syncStatus === '1' ? '停用' : '启用'}当前站点同步数据吗？`"
            @confirm="() => handleSyncStatus(record)"
          >
            <template slot="icon">
              <a-icon v-if="record.syncStatus === '1'" type="close-circle" style="color: red"></a-icon>
              <a-icon v-else type="check-circle" style="color: green"></a-icon>
            </template>
            <!-- 1:启用 2：停用 -->
            <span :style="{ color: record.syncStatus === '1' ? '#63A103' : '#D9001B' }">{{
              record.syncStatus_dictText
            }}</span>
            <a style="margin-left: 3px; font-size: 16px"
              ><a-icon :type="record.syncStatus === '1' ? 'pause-circle' : 'play-circle'" />
            </a>
          </a-popconfirm>
        </span>
        <!-- 时间 -->
        <span slot="authTimeSlot" slot-scope="text, record">
          <div style="display: flex">
            授权：{{ record.authTime ? moment(record.authTime).format('YYYY/MM/DD HH:mm') : '' }}
          </div>
          <div style="display: flex">
            更新：{{ record.authUpdateTime ? moment(record.authUpdateTime).format('YYYY/MM/DD HH:mm') : '' }}
          </div>
        </span>
        <!-- 备注 -->
        <span slot="remarkSlot" slot-scope="text, record">
          <j-ellipsis :value="text" :length="12" />
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleConfig(record)">店铺配置</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="storeCostChangeRecordHandle(record)">变更记录(含作废)</a>
              </a-menu-item>
              <a-menu-item>
                <j-operate-log :id="record.id"></j-operate-log>
              </a-menu-item>
              <!-- <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item> -->
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>

    <store-auth-amazon-modal ref="modalForm" :storeSiteData="storeSiteData" :costCenterData="costCenterData" @ok="modalFormOk"></store-auth-amazon-modal>
    <store-auth-amazon-site-setting-modal ref="siteModalForm" @ok="modalFormOk"></store-auth-amazon-site-setting-modal>
    <store-cost-change-record ref="recordModalForm" @ok="modalFormOk"></store-cost-change-record>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { filterObj,randomUUID } from '@/utils/util';
import StoreAuthAmazonModal from './modules/StoreAuthAmazonModal'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { getAction, httpAction } from '@/api/manage'
import StoreAuthAmazonSiteSettingModal from './modules/StoreAuthAmazonSiteSettingModal'
import StoreCostChangeRecord from './modules/StoreCostChangeRecord'
import moment from 'moment'
export default {
  name: 'StoreAuthAmazonList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    StoreAuthAmazonModal,
    StoreAuthAmazonSiteSettingModal,
    StoreCostChangeRecord
  },
  data() {
    return {
      description: '店铺授权管理页面',
      queryParam: {
        updateTime_begin: '',
        updateTime_end: '',
        authTime_begin: '',
        authTime_end: '',
      },
      storeSiteData: [], //站点国家数据源
      userDictOptions: [], //负责人
      costCenterData:[],
      dateTimeData: [
        { value: 'updateTime', title: '更新时间' },
        { value: 'authTime', title: '授权时间' },
      ],
      dateTime: 'updateTime', //默认 更新时间
      dateTimeRange: [],
      searchOrgOptions: [],
      replaceFields: {
        key: 'code',
        title: 'name',
        children: 'sites',
        value: 'code',
      },
      replaceFieldsOrg: {
        key: 'key',
        title: 'departName',
        children: 'children',
        value: 'orgCode',
      },
      tipVisibleId: null,
      // 表头
      columns: [
        {
          title: '店铺卖家记号',
          align: 'center',
          dataIndex: 'sellerId',
        },
        {
          title: '店铺名称',
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: '站点',
          align: 'center',
          dataIndex: 'site_dictText',
          scopedSlots: { customRender: 'siteSlot' },
        },
        {
          title: '授权状态',
          align: 'center',
          dataIndex: 'authStatus_dictText',
          scopedSlots: { customRender: 'authStatusSlot' },
        },
        {
          title: '同步状态',
          align: 'center',
          dataIndex: 'syncStatus_dictText',
          scopedSlots: { customRender: 'syncStatusSlot' },
        },
        {
          title: '负责人',
          align: 'center',
          dataIndex: 'director',
        },
        // {
        //   title: '所属组织',
        //   align: 'center',
        //   dataIndex: 'departOrg_dictText',
        // },
        {
          title: '成本中心',
          align: 'center',
          dataIndex: 'costCenterId_dictText',
        },   
        // {
        //   title: '税费',
        //   align: 'center',
        //   dataIndex: 'taxWay_dictText',
        // },
        {
          title: '变更进度',
          align: 'center',
          dataIndex: 'progressStatus_dictText',
          customCell:(record, rowIndex)=>{
           // 0:无记录  1：未生效  2.已生效  3.已作废
           if(record.progressStatus === '1'){
             return { style: { color: '#f59a23' } }
           }else if(record.progressStatus === '2'){
            return { style:{color:'#63a103'} }
           }else if(record.progressStatus === '3'){
            return { style:{color:'#aaaaaa'} }
           }else{
            return { style:{color:'#333333'} }
           }
          }
        },
        {
          title: '新成本中心',
          align: 'center',
          dataIndex: 'costCenterIdAfter_dictText',
        },
        {
          title: '生效/作废时间',
          align: 'center',
          dataIndex: 'effectChangeTime',
          customRender:(text, record, index)=>{
            return text? moment(text).format('YYYY/MM/DD') :''
          }
        },
        {
          title: '时间',
          align: 'center',
          dataIndex: 'authTime',
          scopedSlots: { customRender: 'authTimeSlot' },
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'remarkSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/oms/store/storeAuthAmazon/list',
        delete: '/oms/store/storeAuthAmazon/delete',
        deleteBatch: '/oms/store/storeAuthAmazon/deleteBatch',
        exportXlsUrl: '/oms/store/storeAuthAmazon/exportXls',
        importExcelUrl: '/oms/store/storeAuthAmazon/importExcel',
        queryStoreSite: '/oms/site/storeSite/queryRegionSite',
        authUrl: '/oms/openApi/amazon/authUrl',
        edit: '/oms/store/storeAuthAmazon/edit',
        getAllUsernameByOrg: '/sys/user/getAllUsernameByOrg',
        queryTreeListByCurrDepart: '/sys/sysDepart/queryTreeListByCurrDepart',
        queryAllByOrgCode:'/sys/costCenter/queryAllByOrgCode',
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
    this.getStoreSiteData()
    this.getAllUsernameByOrgData()
    this.getqueryTreeListByCurrDepart()
    this.getQueryAllByOrgCode()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    moment,
    initDictConfig() {},
    selectRowData(record, index) {
      const that = this
      return {
        on: {
          dblclick: () => {
            this.handleDetail(record)
          },
        },
      }
    },
    //重置
    searchReset() {
      this.queryParam = {}
      this.dateTimeRange = []
      this.loadData(1)
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if(this.superQueryParams){
        sqp['superQueryParams']=encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter ,this.filters);
      param.director = this.queryParam.directorArr ? this.queryParam.directorArr.join(',') :''
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      delete param.directorArr
      return filterObj(param);
    },
    //显示异常原因
    tipVisibleClick(id) {
      this.tipVisibleId = id
    },
    //选择下拉日期
    dateTimeSelect(value) {
      this.dateTimeData.forEach((item) => {
        this.$set(this.queryParam, [`${item.value}_begin`], null)
        this.$set(this.queryParam, [`${item.value}_end`], null)
      })
      this.dateTimeRange = []
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    //选择日期
    dateTimeChange(value, dateString) {
      this.$set(this.queryParam, [`${this.dateTime}_begin`], dateString[0])
      this.$set(this.queryParam, [`${this.dateTime}_end`], dateString[1])
    },
    //批量站点设置
    handleBatchSetting() {
      this.$refs.siteModalForm.add(this.selectedRowKeys)
      this.$refs.siteModalForm.title = '批量店铺设置'
      this.$refs.siteModalForm.disableSubmit = false
    },
    //查看店铺成本中心变更记录
    storeCostChangeRecordHandle(record){
      this.$refs.recordModalForm.showModal(record)
    },
    //重新授权
    authAfreshHadnle(record) {
      if (!record.regionCode) {
        this.$message.warning('请选择区域')
      } else {
        getAction(this.url.authUrl, { region: record.regionCode, authId: randomUUID() }).then((res) => {
          if (res.success) {
            if (res.message) {
              window.open(res.message)
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    },
    //启用、停用同步状态
    handleSyncStatus(record) {
      const syncStatus = record.syncStatus === '1' ? '2' : '1'
      record.syncStatus = syncStatus
      httpAction(this.url.edit, record, 'put').then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData(1)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    
    //获取站点数据
    getStoreSiteData() {
      getAction(this.url.queryStoreSite).then((res) => {
        if (res.success) {
          this.storeSiteData = res.result || []
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //获取用户负责人数据
    getAllUsernameByOrgData() {
      getAction(this.url.getAllUsernameByOrg).then((res) => {
        if (res.success) {
          this.userDictOptions =
            res.result?.map((item) => {
              return { label: item, value: item }
            }) || []
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //获取店铺所属组织
    getqueryTreeListByCurrDepart() {
      getAction(this.url.queryTreeListByCurrDepart).then((res) => {
        if (res.success) {
          this.searchOrgOptions = res.result || []
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //获取成本中心数据
    getQueryAllByOrgCode(){
       getAction(this.url.queryAllByOrgCode).then(res=>{
        if(res.success){
         this.costCenterData = res.result ||[]
        }else{
          this.$message.warning(res.message)
        }
       })  
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'name', text: '店铺名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'sellerId', text: '卖家id', dictCode: '' })
      fieldList.push({ type: 'string', value: 'site', text: '站点', dictCode: 'hz_store_site_default,name,id' })
      fieldList.push({ type: 'string', value: 'authStatus', text: '授权状态', dictCode: 'oms_store_auth_status' })
      fieldList.push({ type: 'string', value: 'syncStatus', text: '同步状态', dictCode: 'oms_store_sync_status' })
      fieldList.push({ type: 'datetime', value: 'authTime', text: '授权时间' })
      fieldList.push({ type: 'datetime', value: 'authUpdateTime', text: '授权更新时间' })
      fieldList.push({ type: 'string', value: 'ioss', text: 'ioss', dictCode: '' })
      fieldList.push({ type: 'string', value: 'iossInterCode', text: 'ioss国际代码', dictCode: '' })
      fieldList.push({ type: 'string', value: 'eori', text: 'eori', dictCode: '' })
      fieldList.push({ type: 'string', value: 'eoriInterCode', text: 'eori国际代码', dictCode: '' })
      fieldList.push({ type: 'string', value: 'taxNum', text: '税号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'taxInterCode', text: '税号所属国际代码', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'commissionFee', text: '平台佣金费用', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'vatRate', text: 'vat税率', dictCode: '' })
      fieldList.push({ type: 'string', value: 'taxWay', text: '税费计费方式', dictCode: 'oms_tax_way' })
      this.superFieldList = fieldList
    },
    handleConfig: function (record) {
      this.$refs.modalForm.editConfig(record)
      this.$refs.modalForm.title = '店铺配置'
      this.$refs.modalForm.disableSubmit = false
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';

.error-status {
  color: #d9001bd8;
}
/deep/.ant-calendar-picker {
  width: 100% !important;
}
.error-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/* /deep/ .ant-select-selection--multiple {
  position: relative;
}
/deep/.ant-select-selection {
  z-index: 99;
} */
</style>
<style>
.custom-dropdown {
  z-index: 1050 !important;
}
</style>